<template>
  <div>
    <div class="hender" v-if="false">
      <div class="left" style="display: flex">
        <!-- <img
          src="../../../assets/logo.png"
          height="35px"
          width="70px"
          style="margin: 0 10px 0 20px; margin-top: 12px"
        /> -->
        <div style="color: #333; font-size: 20px; font-weight: 600">AI仿生助理</div>
      </div>
      <!-- <div
        class="right"
        style="margin-right: 30px; font-size: 16px; color: #666"
      >
        <a-button plain size="small" @click="handleDialog"
          ><i class="el-icon-edit"></i> 更新日志</a-button
        >
      </div> -->
    </div>

    <a-row>
      <a-col :span="4">
        <div class="chat-container">
          <a-card
            class="box-card"
            :body-style="{ height: '80vh', padding: '0px', background: '#EBE8E7' }"
            style="background: #f7f7f7"
            title="仿 生 助 理"
          >
            <div :class="['beWsfr_U', activeType == 1 ? 'active' : '']" @click="selectItem(1)">
              <div class="P9ZK1OTT">
                <div class="j88GOXPF j88GOXPF-1"></div>
                <div class="NvHLoWu8">查 询 助 理</div>
              </div>
            </div>

            <div :class="['beWsfr_U', activeType == 2 ? 'active' : '']" style="margin-top: 2px" @click="selectItem(2)">
              <div class="P9ZK1OTT">
                <div class="j88GOXPF"></div>
                <div class="NvHLoWu8">分 析 助 理</div>
              </div>
            </div>
          </a-card>
        </div>
      </a-col>
      <a-col :span="20">
        <div class="chat-container">
          <a-card :title="getTitle" class="box-card" :body-style="{ height: '80vh', background: '#F5F5F5' }">
            <div ref="chatContainer" class="chat-messages">
              <div v-for="message in messages" :key="message.id" class="message" :class="{ 'from-me': message.fromMe }">
                <div :class="['avatar', activeType == 1 ? 'avatar-1' : 'avatar-2']" v-if="!message.fromMe"></div>
                <div class="avatar-me" v-else>
                  {{ message.from }}
                </div>
                <div class="content" :class="{ content1: !message.fromMe }">
                  <!-- {{ message.content }} -->
                  <div class="main" style="padding-left: 10px">
                    <vue-markdown
                      :source="message.content"
                      :breaks="true"
                      :typographer="true"
                      :linkify="true"
                      :highlight="false"
                    ></vue-markdown>
                    <a-spin v-if="message.content == '努力思索中，请耐心等待...'">
                      <a-icon slot="indicator" type="loading" style="font-size: 24px" spin />
                    </a-spin>
                  </div>
                </div>
              </div>
            </div>
            <div style="margin-top: 8px; padding-left: 10px">
              <template v-if="activeType == 1">
                您可以输入
                <a-tag v-for="item in tags" :key="item" @click="tagClick(item)">{{ item }}</a-tag>
              </template>
              <template v-else>
                您可以输入
                <a-tag color="blue" v-for="item in tags2" :key="item" @click="tagClick(item)">{{ item }}</a-tag>
              </template>
            </div>
            <div class="chat-input">
              <a-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 8 }"
                v-model="newMessage"
                @keyup.enter.native="sendMessage"
                placeholder="请输入您想查询的信息..."
                style="margin-right: 10px"
              />
              <div style="width: 100px">
                <a-dropdown-button @click="sendMessage">
                  发 送
                  <a-menu slot="overlay" @click="handleMenuClick">
                    <a-menu-item key="1" @click="audioCHangeWord">
                      <a-tooltip placement="topLeft" title="点击语音识别后，说出您的需求" arrow-point-at-center>
                        <a-icon type="audio" /><span v-if="isListening">语音识别中...</span><span v-else>语音识别</span>
                      </a-tooltip>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown-button>
                <!-- <a-button type="primary" @click="sendMessage" size="large" style="height: 58px; width: 97px"
                  >发 送</a-button
                >
                <a-button type="primary" @click="audioCHangeWord" icon="audio" size="small" style="margin-top: 6px">
                  <span v-if="isListening">语音识别中...</span><span v-else>语音识别</span>
                </a-button> -->
                <!-- <a-checkbox v-model="isAuto" :checked="isAuto"> 自动发送 </a-checkbox> -->
              </div>
            </div>
          </a-card>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script>
// import MarkdownIt from "markdown-it";
import VueMarkdown from 'vue-markdown'
export default {
  components: {
    VueMarkdown,
  },
  data() {
    return {
      baseURL: 'http://120.46.139.139:8003',
      messages: [
        {
          id: 1,
          from: 'You',
          content: '您好，有什么需要我帮助的吗？',
          fromMe: false,
        },
      ],
      messages1: [
        {
          id: 1,
          from: 'You',
          content: '您好，有什么需要我帮助的吗？',
          fromMe: false,
        },
      ],
      messages2: [
        {
          id: 1,
          from: 'You',
          content: '您好，有什么需要我帮助的吗？',
          fromMe: false,
        },
      ],
      newMessage: '',
      resultMessage: '',
      newCode: '',
      access_token: '',
      accessCodeInput: '',
      dayLog: [],
      sessionId: null,
      isListening: false,
      activeType: 1,
      tags: [
        '2236号电解槽2023年6月3号的冷热指数是多少？',
        '查询2023年6月3日2236号电解槽的日报数据，用表格显示',
        '查询2023年6月3日2236号电解槽的工作电压',
        '预测2236号电解槽三天的出铝量',
      ],
      tags2: ['2236号电解槽2023年6月平均值'],
      isAuto: true,
    }
  },
  created() {},
  methods: {
    tagClick(value) {
      this.newMessage = value
      this.sendMessage()
    },
    getTitle() {
      if (this.activeType == 1) {
        this.messages = this.messages1
        return '算法分析助理'
      }
      if (this.activeType == 2) {
        this.messages = this.messages2
        return '智能日报助理'
      }
      return ''
    },
    selectItem(type) {
      if (this.activeType == type) {
        return
      }
      this.activeType = type
      this.newMessage = ''
    },
    sendMessage() {
      var that = this
      if (!this.newMessage.trim()) {
        return
      }
      if (that.activeType == 2) {
        that.$message.warn('功能暂未开放')
        return
      }
      const newId = this.messages.length + 1
      this.messages.push({
        id: newId,
        from: 'Me',
        content: this.newMessage,
        fromMe: true,
      })
      this.newMessage = ''
      const ask = this.messages[this.messages.length - 1].content
      const newResultId = newId + 1
      this.messages.push({
        id: newResultId,
        from: 'You',
        content: '努力思索中，请耐心等待...',
        fromMe: false,
      })
      //聊天框滚动效果
      const chatContainer = this.$refs.chatContainer
      this.$nextTick(() => {
        chatContainer.scrollTop = chatContainer.scrollHeight
      })

      this.$http
        .post(
          this.baseURL + '/chat/dialogue',
          {
            prompt: ask,
            session_id: that.sessionId || undefined, // 避免传递 null
          },
          {
            headers: {
              'x-token': 'lyarc-eff11f4ca97069dcd1e35ffef6087197',
            },
          }
        )
        .then((res) => {
          // debugger
          // if (res.data.result === '访问密码错误,请重新输入') {
          //   this.messages[newId].content = '访问密码错误,请重新输入'
          //   return
          // }
          this.messages[newId].content = ''
          const lines = res.trim().split('\n')
          for (let line of lines) {
            if (line) {
              console.log(line)
              line = line.replace('data: ', '')
              console.log(line)
              const parsedLine = JSON.parse(line)
              if (parsedLine.text == null) {
                continue
              }
              //appendMessage(parsedLine.text, 'bot', botMessageId);\
              that.messages[newId].content += parsedLine.text
              if (!that.sessionId && parsedLine.session_id) {
                that.sessionId = parsedLine.session_id
              }
            }
          }
          this.messages1 = this.messages
          //this.messages[newId].content = md.render(that.messages[newId].content)
          //console.log(md.render(res.data.result));
          this.$nextTick(() => {
            chatContainer.scrollTop = chatContainer.scrollHeight
          })
        })
    },

    audioCHangeWord() {
      var that = this
      that.newMessage = ''
      // 创建SpeechRecognition对象
      // eslint-disable-next-line no-undef
      var recognition = new webkitSpeechRecognition()
      console.log('recognition1', recognition)
      if (!recognition) {
        // eslint-disable-next-line no-undef
        recognition = new SpeechRecognition()
      }
      console.log('recognition2', recognition)
      console.log(11)
      // 设置语言
      recognition.lang = 'zh-CN'
      console.log(22)
      // 开始语音识别
      recognition.start()
      that.isListening = true
      console.log(33)
      // 监听识别结果
      recognition.onresult = function (event) {
        var result = event.results[0][0].transcript
        console.log('监听结果:', result)
        that.newMessage = result
      }

      // 监听错误事件
      recognition.onerror = function (event) {
        that.isListening = false
        that.$message('监听语音失败:' + event.error)
        console.error(event.error)
      }
      // 监听结束事件（包括识别成功、识别错误和用户停止）
      recognition.onend = function () {
        that.isListening = false
        console.log('语音识别停止')
        if (that.isAuto) {
          setTimeout(() => {
            that.sendMessage()
          }, 1500)
        }
      }
    },
  },
}
</script>

<style scoped lang="less">
/deep/.el-dialog {
  width: 40%;
}
@media screen and (max-width: 700px) {
  /deep/.el-dialog {
    width: 80%;
  }
}
.chat-container {
  box-sizing: border-box;
  height: 80vh;
  width: 100%;
  padding: 10px 0px;
}
.hender {
  line-height: 60px;
  display: flex;
  padding: 10px;
  background-color: #fff;
  border-bottom: 1px solid #ddd;
  vertical-align: bottom;
  align-items: center;
  justify-content: space-between;
}
.chat-messages {
  height: 80%;
  overflow-y: auto;
  border-bottom: 1px solid #ddd;
}

.message {
  display: flex;
  align-items: center;
  margin: 10px;
}

.from-me {
  flex-direction: row-reverse;
}

.avatar {
  min-width: 40px;
  height: 40px;
  background-color: #f4f6f8;
  background-repeat: repeat-x;
  background-size: cover;
  border-radius: 5%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #fff;
}
.avatar-1 {
  background-image: url('../../../assets/icon-select.png');
}
.avatar-2 {
  //background: linear-gradient(322deg, #1f6ff5 7.93%, #9a7ffc 92.22%);
  background-image: url('../../../assets/icon-assay.png');
}
.avatar-me {
  min-width: 40px;
  height: 40px;
  background-color: #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: #fff;
}

.content {
  font-size: 16px;
  margin: 10px;
  padding: 15px 15px 0px 15px;
  border-radius: 5px;
  background-color: #95ec69;
  color: #000;
  text-align: left;
}
.content1 {
  background-color: #fff;
  color: #000;
  font-size: 14px;
}
.main {
  /deep/table {
    border-collapse: collapse;
    margin: 10px;
  }
  /deep/th,
  /deep/td {
    border: 1px solid #ccc;
    padding: 10px;
    text-align: center;
  }
}
.chat-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
}
.beWsfr_U {
  align-items: center;
  cursor: pointer;
  display: inline-flex;
  height: 52px;
  justify-content: space-between;
  height: 66px;
  width: 100%;
}
.beWsfr_U:hover {
  background: rgba(136, 134, 151, 0.1);
}
.active {
  background: #c8c7c7;
}
.P9ZK1OTT,
.j88GOXPF {
  align-items: center;
  display: flex;
}
.P9ZK1OTT {
  margin-left: 10px;
}
.j88GOXPF {
  //background: linear-gradient(322deg, #1f6ff5 7.93%, #9a7ffc 92.22%);
  background-image: url('../../../assets/icon-assay.png');
  // border-radius: 4.615px;
  height: 36px;
  justify-content: center;
  width: 36px;
  background-size: cover;
}
.j88GOXPF-1 {
  background-image: url('../../../assets/icon-select.png');
}
.NvHLoWu8 {
  color: #05073b;
  font-family: PingFang SC;
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 20px;
  margin-left: 8px;
  text-align: justify;
}
</style>